import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

import 'package:thrio/thrio.dart';
import 'package:thrio_example/src/models/student.dart';

import '../../models/people.dart';

class Page extends StatefulWidget {
  const Page({
    Key key,
    this.url,
    this.index,
    this.params,
  }) : super(key: key);

  final String url;

  final int index;

  final dynamic params;

  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<Page> {
  final _channel = ThrioChannel(channel: 'custom_thrio_channel');
  @override
  void initState() {
    super.initState();

    //调用 json 解析 demo
    jsonParseDemo();

    //调用 future 事件队列
    eventQueueDemo();

    fileDemo();

    _channel.registryMethodCall('sayHello', ([arguments]) {
      ThrioLogger.v('sayHello from native');
      return null;
    });
  }


  //事件队列
  eventQueueDemo(){

    /*
    //微任务队列（优先级高）
    scheduleMicrotask(() => print('-->> this is a 微任务'));

    //事件队列（优先级低）
    Future(() => print('-->> future 1'));

    Future(() => print('-->> future 2')).
      then((value) => print('and then 1')).
        then((value) => print('and then 2'));
    */
    
    // f1 比 f2 先执行
    Future(() => print('-->> f1'));
    Future(() => print('-->> f2'));

    //f3 执行后，立刻同步执行 then 3
    Future(() => print('-->> f3')).then((value) => print('-->> then 3'));
    
    //then 4 会加入微任务队列，尽快执行
    Future(() => null).then((value) => print('-->> then 4'));
  }

  String jsonString = '''
    {
      "id" : "123",
      "name" : "张三",
      "score" : 95,
      "teacher" : {
        "name": "李四",
        "age" : 40
      }
    }
    ''';

  static Student parseStudent(String content){
    // 将字符串解码成 Map 对象
    var jsonResponse = json.decode(content);

    // 手动解析
    Student student = Student.fromJson(jsonResponse as Map<String, dynamic>);
    return student;
  }

  Future<Student> loadStudent(){

    //将解析工作放到新的 Isolate 中完成，避免造成短期 UI 无法响应
    return compute(parseStudent, jsonString);
  }

  // 解析 json 数据
  jsonParseDemo(){
    loadStudent().then((stu) {
      String content = '''
        name: ${stu.name}
        score: ${stu.score}
        teacher: ${stu.teacher.name}
      ''';
      print('-->> json: $content');
    });
  }
  
  //本地文件读写操作
  fileDemo() {
    _readFileContent().then((value) {
      print('-->> before:$value');

      _writeFileContent('hello world $value .').then((value) {
        _readFileContent().then((value) => print('-->> after:$value'));
      });
    });
  }
  
  //创建本地文件目录
  Future<File> get _localFile async {
    final directory = await getApplicationDocumentsDirectory();
    final path = directory.path;
    return File('$path/content.txt'); //之前这里报错，是由于导错包
  }

  //将字符串写入文件
  Future<File> _writeFileContent(String content) async {
    final file = await _localFile;
    return file.writeAsString(content);
  }

  //从文件中读取字符串
  Future<String> _readFileContent() async {
    try{
      final file = await _localFile;
      String contents = await file.readAsString();
      return contents;

    } catch (error) {
        return '';
    }
  }

  @override
  Widget build(BuildContext context) => NavigatorPageNotify(
      name: 'page2Notify',
      onPageNotify: (params) =>
          ThrioLogger.v('flutter2 receive notify:$params'),
      child: Scaffold(
          appBar: AppBar(
            brightness: Brightness.light,
            backgroundColor: Colors.white,
            title: const Text('thrio_example',
                style: TextStyle(color: Colors.black)),
            leading: context.shouldCanPop(const IconButton(
              color: Colors.black,
              tooltip: 'back',
              icon: Icon(Icons.arrow_back_ios),
              onPressed: ThrioNavigator.pop,
            )),
          ),
          body: SingleChildScrollView(
            child: Container(
              margin: const EdgeInsets.all(24),
              child: Column(children: <Widget>[
                Container(
                  margin: const EdgeInsets.only(top: 10, bottom: 20),
                  alignment: AlignmentDirectional.center,
                  child: Text(
                    'flutter2: index is ${widget.index}',
                    style: const TextStyle(fontSize: 28, color: Colors.blue),
                  ),
                ),
                InkWell(
                  onTap: () => ThrioNavigator.push(
                    url: '/biz1/flutter3',
                    params: {
                      '1': {'2': '3'}
                    },
                  ),
                  child: Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.all(8),
                      color: Colors.yellow,
                      child: const Text(
                        'push flutter3',
                        style: TextStyle(fontSize: 22, color: Colors.black),
                      )),
                ),
                InkWell(
                  onTap: () => ThrioNavigator.remove(url: '/biz2/flutter2'),
                  child: Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.all(8),
                      color: Colors.yellow,
                      child: const Text(
                        'remove flutter2',
                        style: TextStyle(fontSize: 22, color: Colors.black),
                      )),
                ),
                InkWell(
                  onTap: () => ThrioNavigator.pop(
                      params: People(name: '大宝剑', age: 0, sex: 'x')),
                  child: Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.all(8),
                      color: Colors.yellow,
                      child: const Text(
                        'pop',
                        style: TextStyle(fontSize: 22, color: Colors.black),
                      )),
                ),
                InkWell(
                  onTap: () => ThrioNavigator.push(
                      url: '/biz2/native2',
                      params: {
                        '1': {'2': '3'}
                      },
                      poppedResult: (params) =>
                          ThrioLogger.v('/biz1/native1 popped:$params')),
                  child: Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.all(8),
                      color: Colors.grey,
                      child: const Text(
                        'push native2',
                        style: TextStyle(fontSize: 22, color: Colors.black),
                      )),
                ),
                InkWell(
                  onTap: () => ThrioNavigator.remove(url: '/biz1/native1'),
                  child: Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.all(8),
                      color: Colors.grey,
                      child: const Text(
                        'pop native1',
                        style: TextStyle(fontSize: 22, color: Colors.black),
                      )),
                ),
                InkWell(
                  onTap: () {
                    ThrioNavigator.notify(
                        url: '/biz1/flutter1',
                        name: 'page1Notify',
                        params: People(name: '大宝剑', age: 1, sex: 'x'));
                  },
                  child: Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.all(8),
                      color: Colors.grey,
                      child: const Text(
                        'notify flutter1',
                        style: TextStyle(fontSize: 22, color: Colors.black),
                      )),
                ),
                InkWell(
                  onTap: () {
                    ThrioNavigator.notify(
                        url: '/biz2/flutter2',
                        name: 'page2Notify',
                        params: People(name: '大宝剑', age: 2, sex: 'x'));
                  },
                  child: Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.all(8),
                      color: Colors.grey,
                      child: const Text(
                        'notify flutter2',
                        style: TextStyle(fontSize: 22, color: Colors.black),
                      )),
                ),
                InkWell(
                  onTap: () {
                    ThrioNavigator.notify(
                        name: 'all_page_notify_from_flutter2',
                        params: People(name: '大宝剑', age: 2, sex: 'x'));
                  },
                  child: Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.all(8),
                      color: Colors.grey,
                      child: const Text(
                        'notify all',
                        style: TextStyle(fontSize: 22, color: Colors.black),
                      )),
                ),
              ]),
            ),
          )));
}
